package handlers

import (
	"net/http"
	"strings"
	"time"

	"zwai-app/config"
	"zwai-app/middleware"
	"zwai-app/services"
	"zwai-app/util"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

// userInfoResponse 当前用户详情返回结构
type userInfoResponse struct {
	UserID          string `json:"userId"`
	Account         string `json:"account"`
	Username        string `json:"username"`
	MembershipLevel int    `json:"membershipLevel"`
	Points          int    `json:"points"`
	InviteCode      string `json:"inviteCode"`
	InvitedBy       string `json:"invitedBy,omitempty"`
	CreatedAt       string `json:"created_at"`
	Age             int    `json:"age"`
	Gender          string `json:"gender"`
	Birthday        string `json:"birthday"`
	Hobbies         string `json:"hobbies"`
	Address         string `json:"address"`
	Email           string `json:"email"`
	Signature       string `json:"signature"`
	AvatarURL       string `json:"avatarUrl"`
}

// simpleUser 用于粉丝/关注列表
type simpleUser struct {
	UserID   string `json:"userId"`
	Account  string `json:"account"`
	Username string `json:"username"`
}

// RegisterUserInfoRoutes 注册用户相关路由
func RegisterUserInfoRoutes(mux *http.ServeMux, cfg config.Config) {
	// /me
	mux.HandleFunc("/me", middleware.AuthMiddleware(meOrUpdateHandler, cfg))

	// /me/invited
	mux.HandleFunc("/me/invited", middleware.AuthMiddleware(invitedHandler, cfg))
	// /me/followers
	mux.HandleFunc("/me/followers", middleware.AuthMiddleware(followersHandler, cfg))
	// /me/following
	mux.HandleFunc("/me/following", middleware.AuthMiddleware(followingHandler, cfg))
	// POST /users/{id}/follow
	mux.HandleFunc("/users/", middleware.AuthMiddleware(userRelationshipHandler, cfg))
}

func meOrUpdateHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		meHandler(w, r)
	case http.MethodPut:
		updateProfileHandler(w, r)
	default:
		util.JSONResponse(w, http.StatusMethodNotAllowed, map[string]interface{}{
			"code": 1, "msg": "只支持 GET 和 PUT",
		})
	}
}

func meHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	userID := middleware.FromContext(r)
	usr, prof, err := services.GetCurrentUser(r.Context(), userID)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 4, "msg": "获取用户信息失败: " + err.Error()})
		return
	}
	resp := userInfoResponse{
		UserID:          usr.ID.Hex(),
		Account:         usr.Account,
		Username:        usr.Username,
		MembershipLevel: prof.MembershipLevel,
		Points:          prof.Points,
		InviteCode:      prof.InviteCode,
		CreatedAt:       usr.CreatedAt.Format(time.RFC3339),
		Age:             prof.Age,
		Gender:          prof.Gender,
		Birthday:        prof.Birthday,
		Hobbies:         prof.Hobbies,
		Address:         prof.Address,
		Email:           prof.Email,
		Signature:       prof.Signature,
		AvatarURL:       prof.AvatarURL,
	}
	if prof.InvitedBy != primitive.NilObjectID {
		resp.InvitedBy = prof.InvitedBy.Hex()
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "查询成功", "data": resp})
}

func invitedHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	userID := middleware.FromContext(r)
	list, err := services.GetInvitedUsers(r.Context(), userID)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 4, "msg": "获取邀请列表失败: " + err.Error()})
		return
	}
	var respList []simpleUser
	for _, u := range list {
		respList = append(respList, simpleUser{
			UserID:   u.UserID,
			Account:  u.Account,
			Username: u.Username,
		})
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "查询成功", "data": respList})
}

func followersHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	userID := middleware.FromContext(r)
	list, err := services.GetFollowers(r.Context(), userID)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 4, "msg": "获取粉丝列表失败: " + err.Error()})
		return
	}
	var respList []simpleUser
	for _, u := range list {
		respList = append(respList, simpleUser{
			UserID:   u.UserID,
			Account:  u.Account,
			Username: u.Username,
		})
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "查询成功", "data": respList})
}

func followingHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	userID := middleware.FromContext(r)
	list, err := services.GetFollowing(r.Context(), userID)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 4, "msg": "获取关注列表失败: " + err.Error()})
		return
	}
	var respList []simpleUser
	for _, u := range list {
		respList = append(respList, simpleUser{
			UserID:   u.UserID,
			Account:  u.Account,
			Username: u.Username,
		})
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "查询成功", "data": respList})
}

func userRelationshipHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	// URL 形如 /users/{id}/follow
	parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
	if len(parts) != 3 || parts[0] != "users" || parts[2] != "follow" {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 2, "msg": "接口不存在"})
		return
	}
	authorID, err := primitive.ObjectIDFromHex(parts[1])
	if err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 3, "msg": "作者ID无效"})
		return
	}
	userID := middleware.FromContext(r)
	uid, _ := primitive.ObjectIDFromHex(userID)
	if err := services.FollowAuthor(r.Context(), authorID, uid); err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 4, "msg": "操作失败: " + err.Error()})
		return
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "操作成功"})
}
